<template>
  <Dialog v-model="dialogVisible" title="批量导入能耗报告数据" width="550px">
    <el-form ref="formRef" v-loading="formLoading" label-width="0">
      <el-form-item>
        <el-alert
          title="请上传JSON格式的数据文件"
          type="info"
          show-icon
          class="mb-4"
          :closable="false"
        >
          <template #default>
            <p class="text-sm mt-1">上传JSON数组文件，包含设备报告数据，格式如示例所示</p>
          </template>
        </el-alert>

        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleFileExceed"
          :on-remove="handleFileRemove"
          action="#"
          accept=".json"
          drag
          class="w-full"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip mt-2">
              只能上传JSON文件(.json)
              <el-tooltip content="示例文件格式" placement="top">
                <el-button link type="primary" class="ml-1" @click="showFormatExample"
                  >查看示例</el-button
                >
              </el-tooltip>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="submitLoading"
        :disabled="!uploadFile"
        @click="handleSubmit"
        >导入</el-button
      >
      <el-button
        type="warning"
        :loading="testLoading"
        :disabled="!uploadFile"
        @click="handleTestUpload"
        >测试上传</el-button
      >
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as ReportApi from '@/api/energy/report'
import { ref } from 'vue'
import { ElMessage, ElMessageBox, UploadInstance, UploadRawFile, UploadFile } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import Dialog from '@/components/Dialog/src/Dialog.vue'

const dialogVisible = ref(false)
const formLoading = ref(false)
const submitLoading = ref(false)
const testLoading = ref(false)
const formRef = ref()
const uploadRef = ref<UploadInstance>()

// 上传的文件
const uploadFile = ref<UploadRawFile | null>(null)

// 处理文件变更
const handleFileChange = (file: UploadFile) => {
  console.log('文件已选择:', file.name, file.size)
  uploadFile.value = file.raw || null
}

// 处理文件超出限制
const handleFileExceed = () => {
  ElMessage.warning('只能上传一个文件')
  // 清空上传列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 处理文件移除
const handleFileRemove = () => {
  uploadFile.value = null
}

// 显示格式示例
const showFormatExample = () => {
  ElMessageBox.alert(
    `<pre style="font-size: 12px;">
[
  {
    "deviceId": "001",
    "reportDataType": "voltage",
    "reportDataValue": 220.5,
    "reportDataLevel": "info", 
    "reportDataTime": "2025-08-13 10:00:00",
    "energyConsumption": 100.5,
    "message": "正常电压波动"
  }
]</pre>`,
    '文件格式示例',
    {
      dangerouslyUseHTMLString: true,
      closeOnClickModal: true,
      confirmButtonText: '关闭'
    }
  )
}

// 处理测试上传
const handleTestUpload = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先上传文件')
    return
  }

  testLoading.value = true
  try {
    console.log('开始测试上传文件:', uploadFile.value?.name, uploadFile.value?.size)
    const res = await ReportApi.testUpload(uploadFile.value)
    console.log('测试上传成功:', res)

    // 显示测试结果
    if (res && res.file) {
      ElMessage.success(
        `测试上传成功，服务器接收到文件: ${res.file.name}, 大小: ${res.file.size}字节`
      )
    } else {
      ElMessage.warning('服务器未正确接收文件')
    }
  } catch (error: any) {
    console.error('测试上传失败', error)
    ElMessage.error(`测试上传失败：${error.message || '未知错误'}`)
  } finally {
    testLoading.value = false
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先上传文件')
    return
  }

  // 确认导入
  try {
    await ElMessageBox.confirm('确定要导入该文件吗？', '确认导入', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch (error) {
    return
  }

  // 直接上传文件到服务器
  submitLoading.value = true
  try {
    console.log('开始上传文件:', uploadFile.value?.name, uploadFile.value?.size)
    // 直接将文件发送到后端
    const res = await ReportApi.importReportDataFile(uploadFile.value)
    console.log('上传成功，导入数据条数:', res)
    ElMessage.success(`成功导入 ${res} 条数据`)

    // 重置表单
    resetForm()

    // 关闭弹窗
    dialogVisible.value = false

    // 触发刷新
    emit('success')
  } catch (error: any) {
    console.error('导入失败', error)
    ElMessage.error(`导入失败：${error.message || '请确保文件内容格式正确'}`)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  uploadFile.value = null
  // 清空上传列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 打开弹窗
const open = () => {
  dialogVisible.value = true
  resetForm()
}

// 定义事件
const emit = defineEmits(['success'])

// 向外暴露方法
defineExpose({ open })
</script>
